package com.supermap.sqlite;

import java.sql.*;
import java.util.logging.Logger;

/**
 * @author liqs
 * @version 1.0
 * @date 2021/11/2 15:31
 */
public class SqliteConnection {

    private static Logger logger = Logger.getLogger(SqliteConnection.class.toString());
    private static Connection conn = null;

    public static Connection getSqliteConnection() {
        if (conn == null) {
            try {
                Class.forName("org.sqlite.JDBC");
                conn = DriverManager.getConnection("jdbc:sqlite:sqlite.db");
                return conn;
            } catch (Exception e) {
                logger.info(e.getMessage());
            }
        }
        return conn;
    }

    public static void creatSqlite() {
            try {
                //连接SQLite的JDBC
                Class.forName("org.sqlite.JDBC");
                //建立一个数据库名zieckey.db的连接，如果不存在就在当前目录下创建
                Connection conn = DriverManager.getConnection("jdbc:sqlite:sqlite.db");
                Statement stat = conn.createStatement();
                // creat table
                stat.executeUpdate("create table tbl1(uuid string, ipfsinfo string);");
                if (isTableExist(conn, "tbl1")) {
                    conn.close();
                } else {
                    stat.executeUpdate("create table tbl1(uuid string, ipfsinfo string);");
                    conn.close();
                }
            } catch (Exception e) {
                logger.info(e.getMessage());
            }
    }


    /**
     * 判断表是否存在
     *
     * @param strTableName 表名
     * @return 是否存在
     */
    static boolean isTableExist(Connection connection, String strTableName) throws SQLException {
        Statement statement = connection.createStatement();
        ResultSet rs = null;
        try {
            // 执行查询语句
            rs = statement.executeQuery("select count(*) from sqlite_master where type = 'table' and name = '" + strTableName + "'");
            if (rs.next()) {
                if (rs.getInt(1) > 0) {
                    return true;
                }
            }
            return false;
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    logger.info(e.toString());
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    logger.info(e.toString());
                }
            }
        }
    }

}
